//
//  UIViewController+XMCommon.m
//  XunMi
//
//  Created by MacBook on 2024/2/18.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "UIViewController+XMCommon.h"
#import <objc/runtime.h>

@implementation UIViewController (XMCommon)

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (viewController == self) {
        [navigationController setNavigationBarHidden:YES animated:animated];
    } else {
        [navigationController setNavigationBarHidden:YES animated:animated];

        //        //系统相册继承自 UINavigationController 这个不能隐藏 所有就直接return
        //        if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
        //            return;
        //        }
        //        //不在本页时，显示真正的navbar
        //        [navigationController setNavigationBarHidden:NO animated:animated];
        //        //当不显示本页时，要么就push到下一页，要么就被pop了，那么就将delegate设置为nil，防止出现BAD ACCESS
        //        //之前将这段代码放在viewDidDisappear和dealloc中，这两种情况可能已经被pop了，self.navigationController为nil，这里采用手动持有navigationController的引用来解决
        //        if (navigationController.delegate == self) {
        //            //如果delegate是自己才设置为nil，因为viewWillAppear调用的比此方法较早，其他controller如果设置了delegate就可能会被误伤
        //            navigationController.delegate = nil;
        //        }
    }
}

/// 模态不全屏
+ (void)load {
    Method m1 = class_getInstanceMethod([self class], @selector(presentViewController:animated:completion:));
    Method m2 = class_getInstanceMethod([self class], @selector(p_presentViewController:animated:completion:));
    method_exchangeImplementations(m1, m2);
}

- (void)p_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^__nullable)(void))completion {
    //设置满屏，不需要小卡片
    if (@available(iOS 13.0, *)) {
        viewControllerToPresent.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    [self p_presentViewController:viewControllerToPresent animated:flag completion:completion];
}

+ (UIViewController *)currentViewController {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    // 要消除警告的代码
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
#pragma clang diagnostic pop
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]) {
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}

+ (UIViewController *)getTargetVCWithVCCls:(Class)cls {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    // 要消除警告的代码
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
#pragma clang diagnostic pop
    UIViewController *targetVC = [self getTargetVCFrom:rootViewController targetCls:cls];
    return targetVC;
}

+ (UIViewController *)getTargetVCFrom:(UIViewController *)rootVC targetCls:(Class)cls {
    __block UIViewController *targetVC;
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        targetVC = [self getTargetVCFrom:[(UITabBarController *)rootVC selectedViewController] targetCls:cls];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]) {
        // 根视图为UINavigationController
        [rootVC.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            if ([obj isKindOfClass:cls]) {
                targetVC = obj;
                *stop = YES;
            }
        }];
    } else {
        // 根视图为非导航类
        targetVC = rootVC;
    }

    return targetVC;
}

+ (UIViewController *)getActivityViewController {
    UIViewController *activityViewController = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    // 要消除警告的代码
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
#pragma clang diagnostic pop
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow *tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }

    NSArray *viewsArray = [window subviews];
    if ([viewsArray count] > 0) {
        UIView *frontView = [viewsArray objectAtIndex:0];

        id nextResponder = [frontView nextResponder];

        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            activityViewController = nextResponder;
        } else {
            activityViewController = window.rootViewController;
        }
    }

    return activityViewController;
}

+ (UIViewController *)rootViewController {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    // 要消除警告的代码
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
#pragma clang diagnostic pop
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

+ (UIViewController *)findBestViewController:(UIViewController *)vc {
    if (vc.presentedViewController) {
        return [self findBestViewController:vc.presentedViewController];
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        UISplitViewController *svc = (UISplitViewController *)vc;
        if (svc.viewControllers.count > 0) {
            return [self findBestViewController:svc.viewControllers.lastObject];
        } else {
            return vc;
        }

    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        UINavigationController *svc = (UINavigationController *)vc;
        if (svc.viewControllers.count > 0) {
            return [self findBestViewController:svc.topViewController];
        } else {
            return vc;
        }
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        UITabBarController *svc = (UITabBarController *)vc;
        if (svc.viewControllers.count > 0) {
            return [self findBestViewController:svc.selectedViewController];
        } else {
            return vc;
        }
    } else {
        return vc;
    }
}

+ (UINavigationController *)currentNavigatonController {
    UIViewController *currentViewController = [UIViewController currentViewController];
    return currentViewController.navigationController;
}

- (void)addChildController:(UIViewController *)childController intoView:(UIView *)view {
    [self addChildViewController:childController];
    [view addSubview:childController.view];
    [childController didMoveToParentViewController:self];
}

- (BOOL)isFromPush {
    //判断是push还是present进来的
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1 && [viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) {
        return YES;
    }
    return NO;
}

@end
